import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import {config} from '../../shared/smartadmin.config';

declare var $: any;
declare var BMap: any;
declare var toWGS84: any;
declare var toMapPointArr: any;
declare var changeTime: any;
@Component({
   selector: 'sa-garbage-sites',
   templateUrl: './garbage-sites.component.html',
   styleUrls:['./garbage-sites.css']
})
export class GarbageSitesComponent implements OnInit {
	tableData:any[] = []; //table数据
	totalCount:number = 0; //分页总条数
	curPage:number = 1; //分页当前页
	pageSize:number = 10; //内置的分页每页条数
	searchKey:string = ''; //搜索keyword
	carList:any[] = []; //车辆数据
	companyId:string = ''; //公司ID
	companyList:any[] = []; //公司数据
	deviceId:string = '';//设备ID
	startTime:string = '';//开始时间
	endTime:string = '';//结束时间
	carNumber:string = ''; //选取车牌号
	
	//站点管理,定位部分
	itemPosition:boolean = false;//是否显示站点地图部分
	itemMarker:any;//表格每一个数据定位的marker
	itemRowData:any;//表格每行定位的行数据
	selectStationView:boolean = false;//是否显示选择站点
	stationNameList=[];//所有站点名的数据
	activeName='';//选中的站点名称
	activeEditName='';//选中需要修改站点名
	
	myMap:any='';
	mapSize:any=15;
	searchPointVal:any='';//搜索的经纬度
	pointIcon=new BMap.Icon("assets/img/trackImage/point.png", new BMap.Size(20, 50));
	
	stationlist:any=[];//站点列表数据数组
	stationMarkerlist:any=[];//站点对应marker数据数组
	
	activeIndex:any = false; //激活点击选中的站点
	isEditStatus:boolean = false;//是否处于编辑状态,true的时候不允许在百度地图上新标注,
	nowStation;//当前操作站点
	
	nowMarker;//当前站点的marker对象
	
//	判断停车点的条件和路线绘制变量
	stopSpeed=1.5; //全局变量，获取速度小于1.5的数据
	distanceLength=30;//全局变量，2点之间的距离，判断车辆是否停止的条件之一
	timeDistance=180000;//全局变量，单位毫秒，2点之间停止的事件，判断车辆是否停止的条件之一
	carTrackLine=[];//全局变量，绘画车辆路线数据对象
	carStopArr=[];//全局变量，车辆速度小于stopSpeed的数据对象

	createPointStatus='flase';//全局变量，控制是否可以点击地图添加覆盖物；当等于、true的时候可以，状态是添加站点的时候，flase是添加完成完成后不允许
	allPoint=[];//所有的点
	surePoint=[];//确认的点
	moveMarker={}//记录标记最后一个点;
	status='';//判定在多组的时候是否执行了删除操作；
	
	//街道表格部分
	tableData_street = []; //table数据
	selected_street= []; //row选择的数据
	temp_street= []; //数据缓存的地方
	loadingIndicator_street: boolean = true; //loading图标
	totalCount_street = 0; //分页总条数
	curPage_street = 1; //分页当前页
	fixPageSize_street = 10; //扩展的pagesize控制
	searchKey_street = ''; //搜索keyword
	selectedRow_street:boolean = false;
	isShowTable:boolean = false;
	isAddStreet:boolean = false;
	
	//新建街道名
	streetCompanyId = '';//街道所属公司id
	addHouseNumber =1000;
	addStreetName='';
	addStreetTitle='新增';
	streetEditId=null;
	
	//通过车辆deviceId查询公司id
	allCarCompany=[];
	editStationName:any;
	
	constructor(private jsonApiService: JsonApiService) {}
	
	//刷新
	refresh(){
		this.load();
	}
	//初始化所有站点
	initStationList () {
		this.myMap.clearOverlays();
		this.stationlist=[];
		let reqdata = 'deviceId=' + this.deviceId;
		this.jsonApiService.http('station/stationList.html',reqdata).subscribe(result=>{
			if(!result.success){
				this.jsonApiService.message(result.message+',请添加站点');
			}
			let mapArr=toMapPointArr(result.data);
			let len=mapArr.length;
			if(len<1){
				let nullStation={'name': '',
						'houseNumber':'',
						'streetName': '', 
						'longitude': '',
						'lantitude':'',
						'deviceId':this.deviceId,
						'id':'null_'+0+0
					}
				let fristItem=[nullStation];
				this.stationlist.push(fristItem);
				this.activeIndex='null_'+0+0;
			}
			else{
				let max=mapArr[len-1].group+1;
				for (let _i=0;_i<max;_i++){
					let group=new Array();
					this.stationlist.push(group);
				}
				let groupLen=this.stationlist.length;
				for( let i = 0; i < len ; i++){
					let x=mapArr[i].group;
					for(let j=0; j<groupLen; j++){
						if(x==j){
							let point=new BMap.Point(mapArr[i].lng, mapArr[i].lat);
							let marker=new BMap.Marker(point,{icon: this.pointIcon});  // 创建标注
							this.myMap.addOverlay(marker);
							mapArr[i].marker=marker;
							let label = new BMap.Label(mapArr[i].name,{offset:new BMap.Size(-10,-15)});
							label.setStyle({
								color : "#2c40d7",
								border:'none',
								padding:'0'
							});
							marker.setLabel(label);
							this.stationlist[j].push(mapArr[i]);
						}
					}
				}
			}
		})
	}
	
	//查找出选定的点
	findStation(tiemId){
		if(this.activeIndex){
			let isAppend=this.fillMustIsNull();
			if(!isAppend){
				return;
			}
		}
		this.activeIndex = tiemId;
		this.isEditStatus=true;  
		let len=this.stationlist.length;
		for( let i = 0; i < len ; i++){
			let x=this.stationlist[i].length;
			for(let j=0; j<x; j++){
				this.stationlist[i][j].marker.disableDragging();
				let id=this.stationlist[i][j].id;
				if(tiemId==id){
					let result=this.stationlist[i][j];
					if(!result.houseNumber){
						result.houseNumber='';
					}
					if(!result.streetName){
						result.streetName='';
					}
					let content = "站点名:" + result.name + "<br/>户籍数:" + result.houseNumber +
					"<br/>所在区域:" + result.streetName + "<br/>所在位置:" +common.twoDecimal(result.lng)+','+ common.twoDecimal(result.lat);
					let point = new BMap.Point(result.lng, result.lat);
					let infoWindow = new BMap.InfoWindow(content,{width: 200, heigth: 150,offset: new BMap.Size(0, -20)});  // 创建信息窗口对象 
					this.myMap.openInfoWindow(infoWindow,point); //开启信息窗口
					this.myMap.centerAndZoom(point, this.mapSize);
					let marker=this.stationlist[i][j].marker;
					this.isEditStatus=true;
					marker.enableDragging();
					let that=this;
					marker.addEventListener("dragend", function(e){
						that.myMap.closeInfoWindow(); 
						that.stationlist[i][j].lng=e.point.lng;
						that.stationlist[i][j].lat=e.point.lat;
					})
				}
			}
		}
	}

	//阻止冒泡
	sotpEven(e){
		e.stopPropagation();
	}
	//判断站点的必要字段是否为空
	fillMustIsNull () {
		let notNull=true;
		let len=this.stationlist.length;
		for (let i=0;i<len;i++){
			let x=this.stationlist[i].length;
			for (let j=0;j<x;j++){
				let obj=this.stationlist[i][j];
				let name=obj.name;
				let lng=obj.lng;
				if(name==''||!lng||lng==''){
					notNull=false;
					this.jsonApiService.message('请检查站点名称是否为空或未确定站点坐标');
				}
			}
		}
		return notNull;
	}
	//添加一个站点
	addStation(param){
		//添加站点时候判断是否有选中的当前站点
		let isAppend=this.fillMustIsNull();
		if(!isAppend){
			return;
		}
		this.isEditStatus=false;
		this.nowMarker=false;
		let len=this.stationlist[param].length;
		let sortId;
		if(len<1){
			sortId=0;
		}else{
			sortId=parseInt(this.stationlist[param][len-1].id.split('_')[1])+1;
		}
		let temObj = {
			'name': '',
			'houseNumber':'',
			'streetName': '', 
			'group':param,
			'index':len-1,
			'longitude': '',
			'lantitude':'',
			'deviceId':this.deviceId,
			'id':'null_'+param+sortId,
		};
		this.stationlist[param].push(temObj);
		this.activeIndex=temObj.id;
	}
	//删除一个站点
	deleteItem ($event,id) {
		$event.stopPropagation();
		this.jsonApiService.confirm_message('此操作将永久删除数据,确认要删除?').then(()=>{
			this.activeIndex=id;
			let len=this.stationlist.length;
			for (let i=0;i<len;i++){
				let _len=this.stationlist[i].length;
				for(let j=0;j<_len;j++){
					let _id=this.stationlist[i][j].id;
					if(id==_id){
						let isSave=false;
						let x=_id.split('_').length;
						if(x<2){
							isSave=true
						}
						if(isSave){
							let  testArr=[];
							testArr.push(id);
							let testStr=JSON.stringify(testArr);
						    let reqdata="ids="+testStr;
							this.jsonApiService.http("station/deleteStation.html", reqdata).subscribe(result => {
								this.jsonApiService.message(result.message);
							})
						}
						this.myMap.removeOverlay(this.stationlist[i][j].marker);
						this.stationlist[i].splice(j,1);  
						this.activeIndex = false; 
						break;
					}
				}
			}
		})
	}
	//添加一组站点
	addGroup () {
		let isAppend=this.fillMustIsNull();
		if(!isAppend){
			return;
		}
		this.nowMarker=false;
		this.isEditStatus=false;
		let len = this.stationlist.length;
		let arr = [];
		let temObj = {
			'name': '',
			'houseNumber':'',
			'streetName': '', 
			'longitude': '',
			'lantitude':'',
			'id':'null_'+len+0,
			'group':len,
			'index':0,
			'deviceId':this.deviceId,
		};
		arr.push(temObj);
		this.stationlist.push(arr);
		this.activeIndex=temObj.id;
	}
	//删除一组站点
	deleteGroup(sort){
		this.jsonApiService.confirm_message('此操作将永久删除这组数据,确认要删除?').then(()=>{
			let len=this.stationlist.length;
			for (let i=0;i<len;i++){
				if(sort==i){
					let _len=this.stationlist[i].length;
					let  delArr=[];
					for(let j=0;j<_len;j++){
						this.myMap.removeOverlay(this.stationlist[i][j].marker);
						let delId=this.stationlist[i][j].id;
						let x=delId.split('_').length;
						if(x<2){
							delArr.push(delId);
						}
						if(delArr.length>0){
							let delArrStr=JSON.stringify(delArr);
						    let reqdata="ids="+delArrStr;
							this.jsonApiService.http("station/deleteStation.html", reqdata).subscribe(result => {
								this.jsonApiService.message(result.message);
							})
						}
					}
					this.stationlist.splice(i,1);
					this.activeIndex = false; 
					break;
				}
			}
		})	
	}
	//提交保存站点
	submitStation(){
		let isAppend=this.fillMustIsNull();
		if(!isAppend){
			return;
		}
		let arr=[];
		let len=this.stationlist.length;
		for (let i=0;i<len;i++){
			let _len=this.stationlist[i].length;
			for(let j=0;j<_len;j++){
				let wgs84=toWGS84(this.stationlist[i][j]);
				wgs84.longitude=wgs84.lng;
				wgs84.lantitude=wgs84.lat;
				arr.push(wgs84);
			}
		}
		for(let _x=0;_x<arr.length;_x++){
			let len=arr[_x].id.split('_').length;
			arr[_x].marker='';
			if(len>1){
				arr[_x].id=null;
			}
		}
	    let reqdata="list="+JSON.stringify(arr);
		this.jsonApiService.http("station/addStation.html", reqdata).subscribe(result => {
			this.jsonApiService.message(result.message);
			this.activeIndex=false;
			this.initStationList();
		})
	}
	drawTrack () {
		let startTime=$('#datetimepicker1').val();
		let endTime=$('#datetimepicker2').val();
		if(startTime.split(' ')[0]!==endTime.split(' ')[0]){
			this.jsonApiService.message('只能查看同一天数据');
			return;
		}
		let reqdata = 'deviceId=' + this.deviceId + '&startTime=' + startTime + '&endTime=' + endTime;
		this.jsonApiService.http("track/localtrack.html", reqdata).subscribe(result => {
			if(result.success){
				let mapArr=toMapPointArr(result.data);
				let len=mapArr.length;
				let lineArr=[];
				let stopArr=[];
				for (let i =0;i<len;i++){
					lineArr.push(new BMap.Point(mapArr[i].lng,mapArr[i].lat));
					if(mapArr[i].speed<this.stopSpeed){
						let obj=mapArr[i];
						obj.loc_time=changeTime(mapArr[i].uploadDate),
        				stopArr.push(obj);
        			}
				}
				var polyline = new BMap.Polyline(lineArr, {strokeColor:"#18a45b", strokeWeight:8, strokeOpacity:0.7,enableClicking: false}); 
				this.myMap.addOverlay(polyline);
				this.jsonApiService.message('路线加载成功');
				this.stopMarker(stopArr);
				this.openRowInfo();
			}
			else{
				this.jsonApiService.message(result.message)
			}
		})
	}
	//打开每一行的数据的infobox
	openRowInfo(){
		common.pointGetAdress(this.itemRowData).then(function(address){
			var html='<div class="infoBox">'+
				'<a></a>'+
				'<div class="content">'+
					'<ul>'+
						'<li><span class="leftSpan">站点名称：</span><span class="rightSpan"> '+this.itemRowData.stationName+'</span></li>'+
						'<li><span class="leftSpan">所属公司：</span><span class="rightSpan"> '+this.itemRowData.companyName+'</span></li>'+
						'<li><span class="leftSpan">清运重量：</span><span class="rightSpan"> '+common.twoDecimal(this.itemRowData.weight)+this.itemRowData.weightUnit+'</span></li>'+
						'<li><span class="leftSpan">所在位置：</span><span class="rightSpan"> '+address+'</span></li>'+
						'<li><span class="leftSpan">更新时间：</span><span class="rightSpan"> '+this.itemRowData.uploadDate+'</span></li>'+
					'</ul>'+
				'</div>'+
			'</div>';
		var opts = {
	  		width : 200,     // 信息窗口宽度
			title : this.itemRowData.carNumber+" [ ID "+this.itemRowData.deviceId+"]" , // 信息窗口标题	 
		}
		var infoWindow = new BMap.InfoWindow(html, opts);  // 创建信息窗口对象 
		var point = new BMap.Point(this.itemRowData.lng,this.itemRowData.lat);
		this.myMap.openInfoWindow(infoWindow,point); //开启信息窗口
		setTimeout(function() {
			if($('.pointer').length<1){
				$('.BMap_bottom').append('<div class="pointer"></div>');
			}
		}, 50);
		}.bind(this))
	}
	
	stopMarker (pointArr) {
		let stopPoint=[];
		let len=pointArr.length-1;
		for(let i=0;i<len;i++){
   			let point1=pointArr[i];
   			let point2=pointArr[i+1];
   			let distance=this.caculationDistance(point1,point2);
   			if(distance>this.distanceLength){
   				stopPoint.push(point1);
   			}
   		}
		if(stopPoint.length<1){
   			return;
   		}
		let stopLen=stopPoint.length;
		let stopTime=[];
		for(var  i=0;i<stopLen;i++){
   			var point=stopPoint[i];
   			var a=pointArr.indexOf(point);//取得每个停车点是在pointArr的第几个值取得的；
   			if(i<1){
   				stopTime.push(point.loc_time-pointArr[0].loc_time);
   			}
   			else{
   				var s=pointArr.indexOf(stopPoint[i-1]);//取得上个停车点在总数组中的排序
   				var y=pointArr[s+1];  //取得当前停车点开始进入停车状态的坐标；
   				var timeCha=point.loc_time-y.loc_time;
   				stopTime.push(timeCha);
   			}
   		}
		let that=this;
		let myIcon = new BMap.Icon('assets/img/trackImage/stop.png', new BMap.Size(20, 30));
		for(var i=0;i<stopTime.length;i++){
			 if(stopTime[i]>this.timeDistance){

				 let carPosition = new BMap.Point(stopPoint[i].lng, stopPoint[i].lat);
				 let marker = new BMap.Marker(carPosition,{icon: myIcon});  // 创建标注
				 let content = '<div style="text-align: center;">'+
	   				'<div><img src="assets/img/trackImage/stop2.png" style="width:10%;position: absolute;left: 0; bottom: 8px;" /></div>'+
	   				'<div>载重量：'+stopPoint[i].weight+'（吨）</div>'+
	   				'<div style="line-height:45px;">停车约：'+that.numberTotime(stopTime[i]);+'</div>'+
	   				'</div>';
				 this.myMap.addOverlay(marker);
				 this.addClickHandler(content,marker);
			}
		}
	}
	addClickHandler (content,marker) {
		let that=this;
		marker.addEventListener("click",function(e){
			let point = new BMap.Point(marker.point.lng,marker.point.lat);
			let infoWindow = new BMap.InfoWindow(content,{width: 100, heigth: 150});  // 创建信息窗口对象 
			that.myMap.openInfoWindow(infoWindow,point); //开启信息窗口
		});
	}
	
	//毫秒转换为时间
	numberTotime (data){
		let result=data/1000;
		let d=Math.floor(result/(3600*24));
		let h=Math.floor(result/3600%24);
		let m=Math.floor(result/60%60);
		let s=Math.floor(result%60);
		if(d<1){
			return h+'小时'+m+'分'+s+'秒';
		}
		else{
			return d+"天"+h+'小时'+m+'分'+s+'秒';
		}
	}
	
	caculationDistance(point1,point2) {
	   		let lng1=point1.lng;
	   		let lat1=point1.lat;
	   		let lat2=point2.lat;
	   		let lng2=point2.lng;
			let radius=6371393;//地球半径(米);
	     	let	radLat1 = lat1 * Math.PI / 180.0;
	      	let radLat2 = lat2 * Math.PI / 180.0;
	       	let a = radLat1 - radLat2;
	       	let b = (lng1 -lng2) * Math.PI / 180.0;
	       
	       	let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b/2),2)));
	       	s = s * radius;
		    return s;
	  }
	//表格部分相关 start
	//表格加载
	load_street() {
		let reqdata = 'gridPager={"pageSize":' + this.fixPageSize_street + ',"nowPage":' + this.curPage_street + ',"parameters":{"searchKey":"' + this.searchKey_street+ '"}}'
		this.jsonApiService.http("station/streetpage.html", reqdata).subscribe(data => {
			this.tableData_street = data.exhibitDatas;
			this.totalCount_street = data.recordCount;
		})
	}
	
	//  分页事件回调
	setPage_street(e) {
		this.curPage_street = e.page+1;
		this.load_street();
	}
	//  分页pageSize回调事件
	updatePageSize_street(e) {
		this.curPage_street = 1;
		this.fixPageSize_street = parseInt(e);
		this.load_street();
	}
	//	表格搜索
	table_search_street(word) {
		this.curPage_street = 1
		this.searchKey = common.stringTrim(this.searchKey);
		this.load_street();
	}
	/**拖动list*/	
	
	tableMove(){
		$('body').delegate('.listTabel','mousedown',function(e){
			$(this).css("cursor","move");
			var offset = $(this).position();
			var x = e.pageX - offset.left;
			var y = e.pageY - offset.top;
			$(document).bind("mousemove",function(ev){ 
				$(".listTabel").stop();
				var _x = ev.pageX - x;
				var _y = ev.pageY - y;
				$(".listTabel").animate({left:_x+"px",top:_y+"px"},2);  
		    });  
		});
	    $(document).mouseup(function(){  
            $(".listTabel").css("cursor","default");  
            $(this).unbind("mousemove");  
        }); 
		
	}
	//打开或关闭表格
	isTableOpen(param){
		if(param=='open'){
			this.isShowTable=true;
		}
		else{
			this.isShowTable=false;
		}
	}
	//打开或关闭添加街道模块
	isStreetAppend(param){
		if(param=='open'){
			this.addStreetTitle='新增';
			this.addStreetName='';
			this.addHouseNumber =1000;
			this.streetEditId=null;
			this.isAddStreet=true;
		}
		else{
			this.isAddStreet=false;
		}
	}
	//	表格修改街道
	editStreet(row){
		this.streetCompanyId = row.companyId;
		this.addStreetTitle='编辑';
		this.addStreetName=row.streetName;
		this.addHouseNumber =row.houseNumber;
		this.streetEditId=row.id;
		this.isAddStreet=true;
	}
	
	//提交添加/修改的区域信息
	submitStreet(){
		if(this.addStreetName==''){
			this.jsonApiService.message('请输入区域名');
			return;
		}
		let editId=null;
		if(this.streetEditId){
			editId=this.streetEditId;
		}
		let reqdata ='id=' + this.streetEditId+'&companyId=' + this.streetCompanyId+'&deviceId='+this.deviceId+'&streetName='+this.addStreetName+'&houseNumber='+this.addHouseNumber;
		this.jsonApiService.http('station/addstreet.html',reqdata).subscribe(result=>{
			if(result.success){
				this.load_street();
				this.isAddStreet=false;
			}
			else{
				this.jsonApiService.message(result.message);
			}
		})		
	}
//	区域列表中的删除区信息
	removeStreet(row){		
		this.jsonApiService.confirm_message('此操作将永久删除数据,确认要删除?').then(()=>{
			let  delArr=[];
			delArr.push(row.id);
		    let reqdata="ids="+JSON.stringify(delArr);
			this.jsonApiService.http("station/delStreet.html", reqdata).subscribe(result => {
				this.jsonApiService.message(result.message);
				this.load_street();
			})
		})
	}
	
	//表格选中街道
	selectStreet(row){		
		let len=this.stationlist.length;		
		for( let i = 0; i < len ; i++){						
			let x=this.stationlist[i].length;
			for(let j=0; j<x; j++){
				let id=this.stationlist[i][j].id;
				if(this.activeIndex==id){
					this.stationlist[i][j].houseNumber=row.houseNumber;
					this.stationlist[i][j].streetName=row.streetName;
				}
			}
		}
	}
//	表格部分相关 end
	initSearch () {
		let mp=this.myMap;
		let ac = new BMap.Autocomplete(    //建立一个自动完成的对象
			{"input" : "suggestId"
			,"location" : mp
		});
		ac.addEventListener("onhighlight", function(e) {  //鼠标放在下拉列表上的事件
			let str = "";
			let _value = e.fromitem.value;
			let value = "";
			if (e.fromitem.index > -1) {
				value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
			}    
			str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;
			value = "";
			if (e.toitem.index > -1) {
				_value = e.toitem.value;
				value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
			}    
			str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
			$("#searchResultPanel").text(str);
			let myValue;
			ac.addEventListener("onconfirm", function(e) {    //鼠标点击下拉列表后的事件和点击 
				let _value = e.item.value;
				myValue = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
				$("#searchResultPanel").text("onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue);
				
				setPlace();
			});
			$('#search').click(function(){
				myValue=$('#suggestId').val();
		    	if(myValue!==''){
		    		setPlace();
		    	}
			});
			let setPlace=function (){
				let myFun=function (){
					let pp = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果
					mp.centerAndZoom(pp, 18);
				}
			
			let local = new BMap.LocalSearch(mp, { //智能搜索
			  onSearchComplete: myFun
			});
			
			local.search(myValue);			
		}
		});		
	}
	searchPoint(){
		let val=this.searchPointVal.split(',');
		if(val==''){
			return;
		}
		let point={lng:val[0],lat:val[1]};
//		let marker = new BMap.Marker(point);  // 创建标注
//		this.myMap.addOverlay(marker);              // 将标注添加到地图中
		this.myMap.centerAndZoom(new BMap.Point(point.lng, point.lat), 16);
	}
	baiduMap: any;
	//车辆定位
	position(row) {
		if(this.itemMarker){
			this.myMap.removeOverlay(this.itemMarker);
		}
		this.itemPosition=true;
		this.deviceId=row.deviceId;
		this.itemRowData=row;
		this.jsonApiService.http("realtime/getRealTimeDataForBase.html", 'deviceId=' + this.deviceId).subscribe(result => {
			if(result.data.unit=='1'){
				this.itemRowData.weightUnit=' 吨';	
			}
			else{
				this.itemRowData.weightUnit=' 千克';	
			}
			this.itemRowData.companyName=result.data.companyName;
		})
//		let company=this.getCarCompany(this.deviceId);
//		if(company){
//			this.companyId=company;
//		}
		this.initStationList();
		this.load_street();
		this.itemMarker=new BMap.Marker(new BMap.Point(row.lng,row.lat));
		this.myMap.addOverlay(this.itemMarker);
		var that=this;
		setTimeout(function(){
			that.myMap.centerAndZoom(new BMap.Point(row.lng,row.lat), that.mapSize);
		},100)

		this.baiduMap = that.myMap
	}
	//初始化选择站点名称列表
	initStationNameList () {
		let reqdata = 'deviceId=' + this.deviceId;
		this.jsonApiService.http('station/list.html',reqdata).subscribe(result=>{
			this.stationNameList=result.data;
		})
	}
	//站点修改
	fix_position(row,val) {
		val.show();
		this.selectStationView=true;
		this.editStationName=row;
		this.deviceId=row.deviceId;
		this.initStationNameList();
		
	}
	cancelPosition(val){
		val.hide();
	}
//	//关闭修改站点名选择框
//	closeStationView(){
//		this.selectStationView=false;
//	}
	//选中站点名进行修改
	selectStationName(row,val){
		this.jsonApiService.confirm_message('是否确定修改站点名称').then(()=>{
			let data=[{
					id : this.editStationName.id,
					stationName : row.name, 
					stationId :this.editStationName.stationId
				}];
			let reqdata='list='+JSON.stringify(data);
			this.jsonApiService.http('stats/updaterawdataList.html',reqdata).subscribe(result=>{
				this.jsonApiService.message(result.message);
				if(result.success){
					let index=this.tableData.indexOf(this.editStationName);
					this.tableData[index].stationName=row.name;
					val.hide();
				}
			})
		});
		
	}
	ngOnDestroy(){
		document.onclick = null;
	}
	ngOnInit() {
		this.initCarTree();
		this.initDate().then(()=>this.load());		
		let  that=this;
		that.myMap=new BMap.Map("baiduMap",{enableMapClick: false});//我的地图		
		let point = new BMap.Point(119.5, 24.5);
		let infoWindow = new BMap.InfoWindow('',{width: 200, heigth: 150,offset: new BMap.Size(0, -20)});  //初始化一个信息窗口
		that.myMap.openInfoWindow(infoWindow,point); //开启信息窗口
		setTimeout(function(){
			$('.BMap_bottom').append('<div class="pointer"></div>');
			that.myMap.closeInfoWindow();
		},10)
		that.myMap.centerAndZoom(new BMap.Point(113.46, 22.27), 10);  // 初始化地图,设置中心点坐标和地图级别
		that.myMap.addEventListener("zoomend", function(){   
			that.mapSize=this.getZoom();
		});
		that.myMap.enableScrollWheelZoom(true);     //开启鼠标滚轮缩放
		that.initSearch();//开启搜索匹配功能
		this.tableMove();//表单开启可拖动		
		this.initTrackDate();
		//地图点击事件
		that.myMap.addEventListener("click",function(e){
			if(e.overlay){
				if(that.activeIndex){
					let isAppend=that.fillMustIsNull();
					if(!isAppend){
						return;
					}
				}
				let lng=e.overlay.point.lng;
				let lat=e.overlay.point.lat;
				let len=that.stationlist.length;
				for (let i=0;i<len;i++){
					let _len=that.stationlist[i].length;
					for(let j=0;j<_len;j++){
						let result=that.stationlist[i][j];
						let _lng=result.lng;
						let _lat=result.lat;
						result.marker.disableDragging();
						if(lng==_lng&&lat==_lat){
							that.isEditStatus=true;
							that.activeIndex=result.id;
							let marker=result.marker;
							that.myMap.closeInfoWindow(); 
							marker.enableDragging();
							marker.addEventListener("dragend", function(e){
								that.stationlist[i][j].lng=e.point.lng;
								that.stationlist[i][j].lat=e.point.lat;
							})
							
						}
					}
				}

			}	
			else{
				if(!that.activeIndex || that.isEditStatus){
					return;
				}
				if(that.nowMarker){
					that.myMap.removeOverlay(that.nowMarker);
				}
				let point=e.point;
				let marker=new BMap.Marker(point,{icon: that.pointIcon});
				marker.enableDragging();
				let len=that.stationlist.length;
				for (let i=0;i<len;i++){
					let x=that.stationlist[i].length;
					for (let j=0;j<x;j++){
						if(that.stationlist[i][j].id==that.activeIndex){
							that.stationlist[i][j].lng=e.point.lng;
							that.stationlist[i][j].lat=e.point.lat;
							that.stationlist[i][j].marker=marker;
							that.myMap.addOverlay(marker);
							that.nowMarker=marker;  // 当前站点标注
							marker.addEventListener("dragend", function(e){
								that.stationlist[i][j].lng=e.point.lng;
								that.stationlist[i][j].lat=e.point.lat;
				   				//marker.disableDragging();
				   			})
							marker.addEventListener("click",function(e){
								let isAppend=that.fillMustIsNull();
								if(!that.activeIndex){
									isAppend=that.fillMustIsNull();
								}
								if(!isAppend){
									return;
								}
								that.activeIndex=that.stationlist[i][j].id;
							})
							
						}
					}
				}
			}
		})
		
	}

	export_totle(){
		if(!this.deviceId){
			this.jsonApiService.message("请选择车牌号");
			return
		}
		this.startTime = $("#datetimepicker3").val();
		this.endTime = $("#datetimepicker4").val();
		if(this.startTime==''||this.endTime==''){
			this.jsonApiService.message("起始结束时间不能为空");
			return;
		}
		let timeCheck=common.correctTimeParams(this.startTime,this.endTime,0);
		if(!timeCheck.status){
			this.jsonApiService.message(timeCheck.message);
			return;
		}
		var temdate = new Date();
		var nowTime = temdate.getTime().toString();
		var parameters = {
			deviceId:this.deviceId,
			startTime:this.startTime,
			endTime:this.endTime,
			fileName:this.carNumber+"在["+this.startTime+"至"+this.endTime+"]的载重原始统计",
		}		
		common.exprotDataFile(parameters, 'param', config.BaseURL + 'stats/rawdatalistExport.html')
	}
	getTime(date){
		var year = date.getFullYear();
		var month = (date.getMonth() + 1) < 10 ? "0" + (date.getMonth() + 1) : (date.getMonth() + 1);
		var day = date.getDate()  < 10 ? "0" + date.getDate() : date.getDate();
		return year+"-"+month+"-"+day;
	}
	initDate(){
		var that = this;
		return new Promise(function (resolve, reject) {
			System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(
				()=>{
					System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(()=>{
						
						$("#datetimepicker3").datetimepicker({//时间插件
							format: "yyyy-mm-dd",
						    language: "zh-CN",
						    autoclose: true,
						    minView : 2
						}).on("changeDate", function(e){
							var date = e.date;
							var time = that.getTime(date);
							$("#datetimepicker4").datetimepicker("setStartDate", time);
						});
						$("#datetimepicker4").datetimepicker({//时间插件
							format: "yyyy-mm-dd",
						    language: "zh-CN",
						    autoclose: true,
						    minView : 2
						}).on("changeDate", function(e){
							var date = e.date;
							var time = that.getTime(date);
							$("#datetimepicker3").datetimepicker("setEndDate", time);
						});
//						var date = new Date();
//						$("#datetimepicker4").val(that.getTime(date));//当前时间
//						date.setDate(date.getDate() - 7);//设置前一天
//						$("#datetimepicker3").val(that.getTime(date));
						resolve();
					});
				}
			);
		})
	}
	
	//初始化绘画轨迹日期选择
	initTrackDate(){
		var that = this;
		return new Promise(function (resolve, reject) {
			System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(()=>{
					System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(()=>{
						$("#datetimepicker1").datetimepicker({//时间插件
							format: "yyyy-mm-dd hh:ii:ss",
						    language: "zh-CN",
						    autoclose: true,
//						    minView : 2
						}).on("changeDate", function(e){
							var date = e.date;
							if(!date){return;}
							var time = common.getTimeMmss(date);
							$("#datetimepicker2").datetimepicker("setStartDate", time);
							//选择开始时间.结束时间为当天末时候
							var nowDayEnd=time.slice(0,10)+' 23:59:59';
							$("#datetimepicker2").val(nowDayEnd);
						});
						$("#datetimepicker2").datetimepicker({//时间插件
							format: "yyyy-mm-dd hh:ii:ss",
						    language: "zh-CN",
						    autoclose: true,
//						    minView : 2
						}).on("changeDate", function(e){
							var date = e.date;
							if(!date){return;}
							var time = common.getTimeMmss(date);
							$("#datetimepicker1").datetimepicker("setEndDate", time);
						});
						var trackTime1=$("#datetimepicker1").val();
						var trackTime2=$("#datetimepicker2").val();
						if(trackTime1==''&&trackTime2==''){
							var date = new Date();
							$("#datetimepicker2").val(common.getTimeMmss(date));//当前时间
							date.setDate(date.getDate() - 1);//设置前一天
							$("#datetimepicker1").val(common.getTimeMmss(date));
						}
						resolve();
					});
				}
			);
		})
	}
	//查询
	search_data(){
		this.load();
		this.itemPosition=false;
	}
	//初始化加载list数据
	load() {
		this.startTime = $("#datetimepicker3").val();
		this.endTime = $("#datetimepicker4").val();
		let timeCheck=common.correctTimeParams(this.startTime,this.endTime,0);
		if(!timeCheck.status){
			this.jsonApiService.message(timeCheck.message);
			return;
		}
		let reqdata = 'gridPager={"pageSize":' + this.pageSize + ',"nowPage":' + this.curPage + ',"parameters":{"deviceId":"'+this.deviceId+'","startTime":"'+this.startTime+'","endTime":"'+this.endTime+'"}}';
		this.jsonApiService.http("stats/rawdatalist.html", reqdata).subscribe(data => {
			this.tableData = toMapPointArr(data.exhibitDatas);//将对应的坐标转换成百度坐标系
			this.totalCount = data.recordCount;
			for(let item of data.exhibitDatas){
				item.weight = common.twoDecimal(item.weight);
			}
		})
	}
	//删除所选时间
	del_date(){
		this.startTime = '';
		this.endTime ='';
		$("#datetimepicker1").val('').change();
		$("#datetimepicker2").val('').change();
		$("#datetimepicker2").datetimepicker("setStartDate", null);
		$("#datetimepicker1").datetimepicker("setEndDate", null);
	}
	//分页回调
	paginate(e){
		this.curPage = e.page+1;
		this.pageSize = e.rows;
		this.load();
	}
	//初始化车辆
    initCarTree() {
        System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
            System.import('assets/js/select2-zh-CN.js').then(() => {
                var that = this;
                $("#carNumberSelect2").select2({
                    language: "zh-CN",
                    placeholder: "请选择",
                    minimumInputLength: 2,      //最少2个字符，select2才显示查询的内容
                    ajax: {
                        url: config.BaseURL + "stats/carListByCarNumber.html",
                        dataType: 'json',
                        delay: 50,
                        method: "POST",
                        xhrFields: { withCredentials: true },
                        data: function (params) {
                            return {
                                "carNumber": params.term // search term
                            };
                        },
                        processResults: function(data, params) {
							var options = new Array();
							// 小于10个数量才判断重复
							if(data.data.length<=10){
								let arr = []
								let sameCar = []
								// 判断相同的车牌号
								for (let index = 0; index < data.data.length; index++) {
									let car = data.data[index];
									if(arr.indexOf(car.carNumber)!=-1){
										sameCar.push(car.carNumber)
									}else{
										arr.push(car.carNumber);
									}
								}
								$(data.data).each(function(index, car) {
									if(sameCar.indexOf(car.carNumber)!=-1){
										options.push({
											id: car.deviceId,
											text: car.carNumber+"["+car.parentName+"]"
										})
									}else{
										options.push({
											id: car.deviceId,
											text: car.carNumber
										})
									}
								});
							}else{
								$(data.data).each(function(index, car) {
									options.push({
										id: car.deviceId,
										text: car.carNumber
									})
								});
							}
							return {
								results: options //获取查询后的结果
							};
						},
                        cache: true
                    },
                    templateResult: this.formatRepo
                }).on("select2:select", function (e) {
                    var data = e.params.data;
                    that.deviceId = data.id;
                    if(data.text.indexOf('[') > 0){
						that.carNumber = data.text.split('[')[0];
					} else {
						that.carNumber = data.text;
					}
                });
            })
        })
	}
	//select2 格式回调函数
    formatRepo(state) {
        if (!state.id) { return state.text };
        var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>');
        return $state;
	}
	//清除车辆选中值
    del_carNumber() {
        this.deviceId = '';
        this.carNumber = '';
        var str = $("<span class='select2-selection__placeholder'>请选择</span>");
        $('#carNumberSelect2').val("");
        $("#select2-carNumberSelect2-container").empty();
        $("#select2-carNumberSelect2-container").attr("title", "");
        $("#select2-carNumberSelect2-container").prepend(str);
    }
}
